package com.example.testapp.ui.balance

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.testapp.R
import com.example.testapp.data.entity.Balance
import com.example.testapp.data.entity.BalanceImage
import com.example.testapp.data.entity.BalanceProcessRecord
import com.google.android.material.progressindicator.LinearProgressIndicator
import java.time.format.DateTimeFormatter

/**
 * 账单详情Fragment
 */
class BalanceDetailFragment : Fragment() {
    private var balanceId: Long = 0
    private lateinit var viewModel: BalanceViewModel
    
    // 视图引用
    private lateinit var amountTextView: TextView
    private lateinit var categoryTextView: TextView
    private lateinit var dateTextView: TextView
    private lateinit var descriptionTextView: TextView
    private lateinit var statusTextView: TextView
    private lateinit var progressIndicator: LinearProgressIndicator
    private lateinit var imagesRecyclerView: RecyclerView
    private lateinit var recordsRecyclerView: RecyclerView
    private lateinit var loadingView: View
    private lateinit var editButton: Button
    private lateinit var deleteButton: Button
    
    // 适配器
    private lateinit var imageAdapter: ImageAdapter
    private lateinit var recordAdapter: ProcessRecordAdapter
    
    // 日期格式化器
    private val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    
    companion object {
        private const val ARG_BALANCE_ID = "balanceId"
        
        fun newInstance(balanceId: Long): BalanceDetailFragment {
            val fragment = BalanceDetailFragment()
            val args = Bundle()
            args.putLong(ARG_BALANCE_ID, balanceId)
            fragment.arguments = args
            return fragment
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            balanceId = it.getLong(ARG_BALANCE_ID, 0)
        }
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_balance_detail, container, false)
        
        // 初始化视图
        amountTextView = rootView.findViewById(R.id.textAmount)
        categoryTextView = rootView.findViewById(R.id.textCategory)
        dateTextView = rootView.findViewById(R.id.textDate)
        descriptionTextView = rootView.findViewById(R.id.textDescription)
        statusTextView = rootView.findViewById(R.id.textStatus)
        progressIndicator = rootView.findViewById(R.id.progressStatus)
        imagesRecyclerView = rootView.findViewById(R.id.recyclerViewImages)
        recordsRecyclerView = rootView.findViewById(R.id.recyclerViewProcessingRecords)
        loadingView = rootView.findViewById(R.id.loadingView)
        editButton = rootView.findViewById(R.id.buttonEdit)
        deleteButton = rootView.findViewById(R.id.buttonDelete)
        
        // 设置RecyclerView
        imagesRecyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        imageAdapter = ImageAdapter(ArrayList())
        imagesRecyclerView.adapter = imageAdapter
        
        recordsRecyclerView.layoutManager = LinearLayoutManager(requireContext())
        recordAdapter = ProcessRecordAdapter(ArrayList()) { recordId -> onRetryClick(recordId) }
        recordsRecyclerView.adapter = recordAdapter
        
        // 设置按钮点击事件
        editButton.setOnClickListener { onEditClick() }
        deleteButton.setOnClickListener { onDeleteClick() }
        
        return rootView
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化ViewModel
        viewModel = ViewModelProvider(requireActivity())[BalanceViewModel::class.java]
        
        // 选择当前账单
        if (balanceId > 0) {
            viewModel.selectBalance(balanceId)
        }
        
        // 观察账单详情
        viewModel.selectedBalance.observe(viewLifecycleOwner) { balance ->
            balance?.let { updateBalanceUI(it) }
        }
        
        // 观察账单图片
        viewModel.balanceImages.observe(viewLifecycleOwner) { images ->
            imageAdapter.updateData(images)
        }
        
        // 观察处理记录
        viewModel.processingRecords.observe(viewLifecycleOwner) { records ->
            recordAdapter.updateData(records)
        }
        
        // 观察操作状态
        viewModel.operationState.observe(viewLifecycleOwner) { state ->
            when (state) {
                is BalanceViewModel.OperationState.Loading -> {
                    loadingView.visibility = View.VISIBLE
                }
                is BalanceViewModel.OperationState.Success -> {
                    loadingView.visibility = View.GONE
                    Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show()
                    
                    if (state.message.contains("删除")) {
                        // 删除成功，返回上一页
                        requireActivity().onBackPressed()
                    }
                }
                is BalanceViewModel.OperationState.Error -> {
                    loadingView.visibility = View.GONE
                    Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show()
                }
                else -> loadingView.visibility = View.GONE
            }
        }
    }
    
    /**
     * 更新账单UI
     */
    private fun updateBalanceUI(balance: Balance) {
        // 设置金额
        val amountText = formatAmount(balance.amount)
        amountTextView.text = amountText
        
        // 设置类别
        val category = balance.categoryName
        categoryTextView.text = category ?: "未分类"
        
        // 设置日期
        val date = balance.billDate?.format(dateFormatter) ?: "未知日期"
        dateTextView.text = date
        
        // 设置描述
        val description = balance.description
        descriptionTextView.text = description ?: "无描述"
        
        // 设置状态
        val status = balance.status ?: Balance.STATUS_PENDING
        val statusText: String
        when (status) {
            Balance.STATUS_PENDING -> {
                statusText = "待处理"
                progressIndicator.progress = 25
            }
            Balance.STATUS_PROCESSING -> {
                statusText = "处理中"
                progressIndicator.progress = 50
            }
            Balance.STATUS_COMPLETED -> {
                statusText = "已完成"
                progressIndicator.progress = 100
            }
            Balance.STATUS_FAILED -> {
                statusText = "处理失败"
                progressIndicator.progress = 0
            }
            else -> {
                statusText = "未知状态"
                progressIndicator.progress = 0
            }
        }
        statusTextView.text = statusText
    }
    
    /**
     * 格式化金额
     */
    private fun formatAmount(amount: Int?): String {
        return if (amount == null) {
            "¥0.00"
        } else {
            String.format("¥%.2f", amount / 100.0)
        }
    }
    
    /**
     * 编辑按钮点击事件
     */
    private fun onEditClick() {
        // TODO: 导航到编辑页面
        // val bundle = Bundle().apply { putLong("balanceId", balanceId) }
        // findNavController().navigate(R.id.action_balanceDetailFragment_to_balanceEditFragment, bundle)
    }
    
    /**
     * 删除按钮点击事件
     */
    private fun onDeleteClick() {
        // TODO: 添加确认对话框
        viewModel.deleteBalance(balanceId)
    }
    
    /**
     * 重试按钮点击事件
     */
    private fun onRetryClick(recordId: Long) {
        viewModel.retryProcessRecord(recordId)
    }
    
    /**
     * 图片适配器
     */
    private class ImageAdapter(
        private var images: List<BalanceImage>
    ) : RecyclerView.Adapter<ImageAdapter.ViewHolder>() {
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_image, parent, false)
            return ViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val image = images[position]
            holder.bind(image)
        }
        
        override fun getItemCount(): Int = images.size
        
        fun updateData(newImages: List<BalanceImage>) {
            this.images = newImages
            notifyDataSetChanged()
        }
        
        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val imageView: ImageView = itemView.findViewById(R.id.imageView)
            private val statusImageView: ImageView = itemView.findViewById(R.id.imageStatus)
            private val textView: TextView = itemView.findViewById(R.id.textStatus)
            
            fun bind(image: BalanceImage) {
                // TODO: 使用图片加载库（如Glide）加载图片
                // Glide.with(imageView).load(image.imagePath).into(imageView)
                
                // 在Kotlin中可以使用when代替Java中的switch
                val statusIcon = when (image.recognitionStatus) {
                    BalanceImage.RECOGNITION_STATUS_PENDING -> R.drawable.ic_pending
                    BalanceImage.RECOGNITION_STATUS_PROCESSING -> R.drawable.ic_processing
                    BalanceImage.RECOGNITION_STATUS_SUCCESS -> R.drawable.ic_success
                    BalanceImage.RECOGNITION_STATUS_FAILED -> R.drawable.ic_error
                    else -> R.drawable.ic_unknown
                }
                
                // 设置状态图标
                statusImageView.setImageResource(statusIcon)
                
                // 设置状态文本
                val statusText = when (image.recognitionStatus) {
                    BalanceImage.RECOGNITION_STATUS_PENDING -> "待识别"
                    BalanceImage.RECOGNITION_STATUS_PROCESSING -> "识别中"
                    BalanceImage.RECOGNITION_STATUS_SUCCESS -> "识别成功"
                    BalanceImage.RECOGNITION_STATUS_FAILED -> "识别失败"
                    else -> "未知状态"
                }
                textView.text = statusText
            }
        }
    }
    
    /**
     * 处理记录适配器
     */
    private class ProcessRecordAdapter(
        private var records: List<BalanceProcessRecord>,
        private val listener: (Long) -> Unit
    ) : RecyclerView.Adapter<ProcessRecordAdapter.ViewHolder>() {
        
        private val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_processing_record, parent, false)
            return ViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val record = records[position]
            holder.bind(record, listener)
        }
        
        override fun getItemCount(): Int = records.size
        
        fun updateData(newRecords: List<BalanceProcessRecord>) {
            this.records = newRecords
            notifyDataSetChanged()
        }
        
        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val textProcessor: TextView = itemView.findViewById(R.id.textProcessor)
            private val textTimestamp: TextView = itemView.findViewById(R.id.textTimestamp)
            private val textResult: TextView = itemView.findViewById(R.id.textResult)
            private val imageStatus: ImageView = itemView.findViewById(R.id.imageStatus)
            private val buttonRetry: Button = itemView.findViewById(R.id.buttonRetry)
            private val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            
            fun bind(record: BalanceProcessRecord, listener: (Long) -> Unit) {
                // 设置处理类型
                val typeText = when (record.processType) {
                    BalanceProcessRecord.PROCESS_TYPE_OCR -> "文字识别"
                    BalanceProcessRecord.PROCESS_TYPE_IMAGE_STORAGE -> "图片存储"
                    BalanceProcessRecord.PROCESS_TYPE_THUMBNAIL -> "缩略图生成"
                    BalanceProcessRecord.PROCESS_TYPE_INFO_EXTRACTION -> "信息提取"
                    else -> "未知类型"
                }
                textProcessor.text = typeText
                
                // 设置处理状态
                val statusIcon = when (record.status) {
                    BalanceProcessRecord.STATUS_PENDING -> R.drawable.ic_pending
                    BalanceProcessRecord.STATUS_PROCESSING -> R.drawable.ic_processing
                    BalanceProcessRecord.STATUS_COMPLETED -> R.drawable.ic_success
                    BalanceProcessRecord.STATUS_FAILED -> R.drawable.ic_error
                    else -> R.drawable.ic_unknown
                }
                imageStatus.setImageResource(statusIcon)
                
                // 设置处理时间
                val timeText = record.startTime?.format(timeFormatter) ?: "暂无时间记录"
                textTimestamp.text = timeText
                
                // 设置处理结果或错误信息
                val resultText = if (record.status == BalanceProcessRecord.STATUS_FAILED && !record.errorMessage.isNullOrEmpty()) {
                    "错误: ${record.errorMessage}"
                } else if (record.status == BalanceProcessRecord.STATUS_COMPLETED) {
                    "处理成功 ${if (record.timeConsumed != null) "(耗时: ${formatTimeConsumed(record.timeConsumed!!)})" else ""}"
                } else {
                    "处理中..."
                }
                textResult.text = resultText
                
                // 设置重试按钮
                if (record.status == BalanceProcessRecord.STATUS_FAILED &&
                        (record.retryCount == null || record.maxRetryCount == null ||
                        record.retryCount!! < record.maxRetryCount!!)) {
                    buttonRetry.visibility = View.VISIBLE
                    buttonRetry.setOnClickListener { record.id?.let { listener(it) } }
                } else {
                    buttonRetry.visibility = View.GONE
                }
            }
            
            private fun formatTimeConsumed(timeConsumed: Int): String {
                return when {
                    timeConsumed < 1000 -> "${timeConsumed}毫秒"
                    timeConsumed < 60000 -> String.format("%.1f秒", timeConsumed / 1000.0)
                    else -> String.format("%d分%d秒", timeConsumed / 60000, (timeConsumed % 60000) / 1000)
                }
            }
        }
    }
} 